import socket  
import os  
  
def send_file_with_string(file_path, string_data, server_ip, server_port):  
    if not os.path.isfile(file_path):  
        print(f"文件 {file_path} 不存在!")  
        return  
  
    # 读取图片文件  
    with open(file_path, 'rb') as file:  
        image_data = file.read()  
  
    # 将字符串编码为字节  
    string_bytes = string_data.encode('utf-8')  
  
    # 创建UDP socket  
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
  
    # 发送数据：首先发送字符串的长度，然后发送字符串，最后发送图片数据  
    try:  
        # 发送字符串长度  
        client_socket.sendto(len(string_bytes).to_bytes(4, 'big'), (server_ip, server_port))  
        # 发送字符串  
        client_socket.sendto(string_bytes, (server_ip, server_port))  
        # 发送图片数据  
        client_socket.sendto(image_data, (server_ip, server_port))  
        print(f"文件 {file_path} 和字符串已发送到 {server_ip}:{server_port}")  
    except Exception as e:  
        print(f"发送文件时出错: {e}")  
    finally:  
        client_socket.close()  
  
if __name__ == '__main__':  
    file_path = 'path_to_your_image.jpg'  # 替换为你的图片路径  
    string_data = "This is a sample string."  
    server_ip = '127.0.0.1'  # 替换为接收端的IP地址  
    server_port = 12345  # 替换为接收端的端口号  
    send_file_with_string(file_path, string_data, server_ip, server_port)